"""
Flask 应用工厂
"""
from flask import Flask
from flask_restful import Api
from flask_cors import CORS
import os
import sys
try:
    from server.config.config import config  # type: ignore
    from server.app import db  # type: ignore
except ModuleNotFoundError:
    # 回退：直接在 server 目录运行
    sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
    from config.config import config  # type: ignore
    from app import db  # type: ignore


def create_app(config_name='default'):
    """创建 Flask 应用实例"""
    app = Flask(__name__)
    # 让 JSON 返回中文而不是 \uXXXX 转义
    app.config['JSON_AS_ASCII'] = False
    
    # 加载配置
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    db.init_app(app)
    CORS(app)
    
    # 创建 API
    api = Api(app)
    
    # 注册路由
    try:
        from server.app.routes.leave import LeaveApplicationResource, LeaveApplicationDetailResource  # type: ignore
        from server.app.routes.application_list import ApplicationListResource  # type: ignore
        from server.app.routes.application_detail import ApplicationDetailResource  # type: ignore
        from server.app.routes.flowable_applications import FlowableApplicationListResource  # type: ignore
        from server.app.routes.flowable_deploy import FlowableDeploymentResource  # type: ignore
        from server.app.routes.tasks import TaskListResource, TaskApprovalResource, TaskDetailResource  # type: ignore
        from server.app.routes.attendance import AttendanceSyncResource, AttendanceListResource  # type: ignore
        from server.app.routes.purchase import PurchaseApplicationResource, PurchaseGenerateResource  # type: ignore
    except ModuleNotFoundError:
        from app.routes.leave import LeaveApplicationResource, LeaveApplicationDetailResource  # type: ignore
        from app.routes.application_list import ApplicationListResource  # type: ignore
        from app.routes.application_detail import ApplicationDetailResource  # type: ignore
        from app.routes.flowable_applications import FlowableApplicationListResource  # type: ignore
        from app.routes.flowable_deploy import FlowableDeploymentResource  # type: ignore
        from app.routes.tasks import TaskListResource, TaskApprovalResource, TaskDetailResource  # type: ignore
        from app.routes.attendance import AttendanceSyncResource, AttendanceListResource  # type: ignore
        from app.routes.purchase import PurchaseApplicationResource, PurchaseGenerateResource  # type: ignore
    
    # 请假/加班申请路由
    api.add_resource(LeaveApplicationResource, '/api/leave/apply', '/api/leave/list', '/api/leave/applications')
    api.add_resource(ApplicationListResource, '/api/applications')
    api.add_resource(ApplicationDetailResource, '/api/applications/<int:application_id>')
    api.add_resource(FlowableApplicationListResource, '/api/applications/flowable')
    api.add_resource(FlowableDeploymentResource, '/api/flowable/deploy')
    api.add_resource(LeaveApplicationDetailResource, '/api/leave/<int:application_id>')
    
    # 任务路由
    api.add_resource(TaskListResource, '/api/tasks/pending')
    api.add_resource(TaskApprovalResource, '/api/tasks/<string:task_id>/approve')
    api.add_resource(TaskDetailResource, '/api/tasks/<string:task_id>/variables')
    
    # 考勤路由（Flowable 回调）
    api.add_resource(AttendanceSyncResource, '/api/attendance/sync')
    api.add_resource(AttendanceListResource, '/api/attendance/list')

    # 采购申请路由
    api.add_resource(PurchaseApplicationResource, '/api/purchase/apply', '/api/purchase/list')
    api.add_resource(PurchaseGenerateResource, '/api/purchase/generate')
    
    # 健康检查
    @app.route('/health')
    def health_check():
        return {'status': 'ok', 'message': 'Server is running'}
    
    # 创建数据库表（确保新增采购表存在）
    with app.app_context():
        db.create_all()
    
    return app
